package com.site.wisdom_construction.controller.batchUploadModel.safetyBatchUpload;

import com.site.wisdom_construction.responseEntity.JsonResult;
import com.site.wisdom_construction.service.safetyModule.SafetyRiskSourceService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Author daiyifei @Date 2022/5/26 @Description
 */
@Api(tags = "安全风险源批量导入接口")
@RestController
@RequestMapping("SafetyBatchUpload")
@CrossOrigin
public class SafetyBatchUploadController {
  @Autowired private SafetyRiskSourceService safetyRiskSourceService;
  /** 定义全局的常量值 */
  private static final String XLS = "xls";
  /** 定义全局的常量值 */
  private static final String XLSX = "xlsx";

  /** logger */
  private Logger logger = LoggerFactory.getLogger(SafetyBatchUploadController.class);

  /**
   * Excel导入
   *
   * @param file 文件对象
   * @return Map<String, Object>
   */
  @ApiOperation(value = "导入风险源", notes = "测试数据:")
  @PostMapping("/importExcel")
  public JsonResult importExcel(@RequestParam("file") MultipartFile file, Integer projectId) {
    List<SafetyBatchUploadData> safetyBatchUploadDataList = new ArrayList<>();
    JsonResult jsonResult = new JsonResult();

    Workbook workbook = null;

    String filename = file.getOriginalFilename();
    try {
      if (filename != null) {
        if (filename.endsWith(XLS)) {
          // 2003
          workbook = new HSSFWorkbook(file.getInputStream());
        } else if (filename.endsWith(XLSX)) {
          // 2007
          workbook = new XSSFWorkbook(file.getInputStream());
        } else {
          throw new Exception("文件不是Excel文件");
        }
      } else {
        logger.error("文件为空");
      }
      // 获取sheet
      Sheet sheet = workbook.getSheet("Sheet1");

      int lastRowNum = sheet.getLastRowNum();
      if (lastRowNum == 0) {
        throw new Exception("请填写行数");
      }

      for (int i = 1; i < lastRowNum + 1; i++) {
        Row row = sheet.getRow(i);
        if (row != null) {
          // 用实体类接收cell单元格内容
          SafetyBatchUploadData safetyBatchUploadData = new SafetyBatchUploadData();

          // 项目id
          safetyBatchUploadData.setProjectId(projectId);

          // 工序
          String riskSourceProcess = getCellValue(row.getCell(0));
          safetyBatchUploadData.setRiskSourceProcess(riskSourceProcess);
          // 风险等级
          String riskSourceGarde = getCellValue(row.getCell(1));
          safetyBatchUploadData.setRiskSourceGarde(riskSourceGarde);
          // 伤害类型
          String riskSourceTypes = getCellValue(row.getCell(1));
          safetyBatchUploadData.setRiskSourceTypes(riskSourceTypes);
          // 危险源
          String riskSourceHazard = getCellValue(row.getCell(1));
          safetyBatchUploadData.setRiskSourceHazard(riskSourceHazard);
          // 控制措施
          String riskSourceMeasures = getCellValue(row.getCell(1));
          safetyBatchUploadData.setRiskSourceMeasures(riskSourceMeasures);

          //                    日期格式化操作 备用
          //                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
          //                    String time = sdf.format(new Date());
          //                    tblFixChange.setCreateTime(time);
          //                    tblFixChange.setModifyTime(time);

          safetyBatchUploadDataList.add(safetyBatchUploadData);
        }
      }
      // 批量插入
      safetyRiskSourceService.insertBatchSafetyRiskSource(safetyBatchUploadDataList);
      jsonResult.setCode(200);
      jsonResult.setMessage("批量导入成功!");
    } catch (Exception e) {
      jsonResult.setCode(20006);
      jsonResult.setMessage("数据异常导入失败,请按照模板填写数据");
      logger.error(e.getMessage(), e);
    }
    return jsonResult;
  }

  /**
   * 获取每个单元格内容
   *
   * @param cell cell
   * @return String
   */
  private String getCellValue(Cell cell) {
    // 单元格内容
    String value = "";
    if (cell != null) {
      // 以下是判断数据的类型
      switch (cell.getCellType()) {
          // 数字
        case HSSFCell.CELL_TYPE_NUMERIC:
          value = cell.getNumericCellValue() + "";
          // 判断cell是不是日期类型的
          if (HSSFDateUtil.isCellDateFormatted(cell)) {
            // 获取日期类型的单元格
            Date date = cell.getDateCellValue();
            if (null != date) {
              value = new SimpleDateFormat("yyyy-MM-dd").format(date);
            } else {
              value = "";
            }
          } else {
            value = new DecimalFormat("0").format(cell.getNumericCellValue());
          }
          break;
          // 字符串
        case HSSFCell.CELL_TYPE_STRING:
          value = cell.getStringCellValue();
          break;
          // Boolean
        case HSSFCell.CELL_TYPE_BOOLEAN:
          value = cell.getBooleanCellValue() + "";
          break;
          // 公式
        case HSSFCell.CELL_TYPE_FORMULA:
          value = cell.getCellFormula() + "";
          break;
          // 空格
        case HSSFCell.CELL_TYPE_BLANK:
          value = "";
          break;
          // 错误
        case HSSFCell.CELL_TYPE_ERROR:
          value = "非法字符";
        default:
          value = "未知类型";
          break;
      }
    }
    return value.trim();
  }
}
